var prefix = "/order/manage";
$(function () {
    $("#province").val("");
    $("#city").val("");

    layui.use('laydate', function () {
        var laydate = layui.laydate;
        laydate.render({
            elem: '#start'
            , type: 'datetime'
        });

        laydate.render({
            elem: '#end'
            , type: 'datetime'
        });
    });

    load();
});
$('#orderTable').on('load-success.bs.table', function (e, data) {
    if (data.total && !data.rows.length) {
        $('#orderTable').bootstrapTable('selectPage').bootstrapTable('refresh');
    }
});

function load() {
    $('#orderTable').bootstrapTable(
        {
            method: 'get', // 服务器数据的请求方式 get or post
            url: prefix + "/juheOrderList", // 服务器数据的加载地址
            showRefresh: true,
            // showToggle : true,
            iconSize: 'outline',
            // toolbar: '#exampleToolbar',
            striped: true, // 设置为true会有隔行变色效果
            dataType: "json", // 服务器返回的数据类型
            pagination: true, // 设置为true会在底部显示分页条
            pageList: [10, 20, 50],
            // queryParamsType : "limit",
            // //设置为limit则会发送符合RESTFull格式的参数
            singleSelect: false, // 设置为true将禁止多选
            // contentType : "application/x-www-form-urlencoded",
            // //发送到服务器的数据编码类型
            pageSize: 10, // 如果设置了分页，每页数据条数
            pageNumber: 1, // 如果设置了分布，首页页码
            // search : true, // 是否显示搜索框
            showColumns: false, // 是否显示内容下拉框（选择显示的列）
            sidePagination: "server", // 设置在哪里进行分页，可选值为"client" 或者
            queryParams: function (params) {
                return {
                    limit: params.limit,
                    offset: params.offset,
                    order: 'desc',
                    ordersn: $.trim($("#queryItem").val()),
                    paystatus: $('#paystatus').val(),
                    startTime: $('#start').val(),
                    endTime: $('#end').val(),
                    payType: $('#payType').val(),
                };
            },
            columns: [
                {
                    field: 'id',
                    title: 'id'
                },
                {
                    field: 'ordersn',
                    title: '订单号'
                },
                {
                    field: 'orderprice',
                    title: '订单总额',
                },
                {
                    field: 'payprice',
                    title: '实际支付价格',
                },
                {
                    field: 'paystatus',
                    title: '支付状态',
                    formatter: function (value, row, index) {
                        if (value == 0) {
                            return '<label class="label label-warning">未支付</label>';
                        } else if (value == 1) {
                            return '<label class="label label-warning">支付中</label>';
                        } else if (value == 2) {
                            return '<label class="label label-success">支付完成</label>';
                        } else if (value == 3) {
                            return '<label class="label label-danger">支付失败</label>';
                        } else if (value == 4) {
                            return '<label class="label label-success">退款成功</label>';
                        } else if (value == 5) {
                            return '<label class="label label-danger">退款失败</label>';
                        } else if (value == 6) {
                            return '<label class="label label-warning">退款申请中</label>';
                        } else {
                            return value;
                        }
                    }
                },
                {
                    field: 'payType',
                    title: '支付类型',
                    formatter: function (value, row, index) {
                        if (value == 2) {
                            return '<label class="label label-success">微信支付</label>';
                        } else if (value == 6) {
                            return '<label class="label label-success">支付宝支付</label>';
                        } else {
                            return value;
                        }
                    }
                },
                {
                    field: 'payno',
                    title: '微信支付单号',
                },
                {
                    field: 'outTradeNo',
                    title: '商品订单',
                },
                {
                    field: 'payTime',
                    title: '支付时间',
                },
                {
                    title: '操作',
                    field: 'id',
                    align: 'center',
                    formatter: function (value, row, index) {

                        var splitAccountInfoStr = '<a class="btn btn-primary btn-xs ' + s_send_goods_h + '" href="#" mce_href="#" title="分账信息" onclick="splitAccountInfo(\''
                            + row.outTradeNo + '\')">' + '<i class="fa fa-upload"></i>分账信息</a>';
                        var refund = '<a class="btn btn-primary btn-xs ' + s_send_goods_h + '" href="#" mce_href="#" title="退款信息" onclick="refundInfo(\''
                            + row.refundNo + '\')">' + '<i class="fa fa-upload"></i>退款信息</a>';
                        if (row.juheOrderRefund) {
                            return splitAccountInfoStr + refund;
                        } else {
                            return splitAccountInfoStr;
                        }
                    }
                }
            ]
        });
}

function reLoad() {
    $('#orderTable').bootstrapTable('refresh');
}

/**
 * 格式化商品列信息
 * @param orderProducts 订单商品列表
 * @param orderSn 订单编号
 */
function formatProductInfo(orderProducts, orderSn) {
    var info = "<span class='label label-light'>订单编号:" + orderSn + "</span>";
    if (orderProducts && orderProducts.length > 0) {
        for (var i = 0; i < orderProducts.length; i++) {
            var item = orderProducts[i];
            var product_status = '';
            var refund = '';
            var l = "";
            if (item.isLiansuo == 1) {
                l = '<span style="color: red;">是该门店门店商品</span>';
            }
            if (item.status === -1) {
                product_status = '<span class="label label-warning">已取消</span>';
                if (item.payStatus === 0) {
                    refund = '<span class="label label-info">未支付</span>';
                } else if (item.payStatus === -1) {
                    refund = '<span class="label label-danger">已退款</span>';
                }
            } else if (item.status === 1) {
                product_status = '<span class="label label-danger">待发货</span>';
                if (orderProducts.length > 1) {
                    refund = '<a shiro:haspermission="order:manage:refund" title="退款"><button class="btn btn-xs btn-danger" onclick="refundSingle(\'' + item.id + '\')">单品退款</button></a>'
                }
            } else if (item.status === 2) {
                product_status = '<span class="label label-success">已发货</span>';
                if (orderProducts.length > 1) {
                    refund = '<a shiro:haspermission="order:manage:refund" title="退款"><button class="btn btn-xs btn-danger" onclick="refundSingle(\'' + item.id + '\')">单品退款</button></a>'
                }
            } else if (item.status === 3) {
                product_status = '<span class="label label-primary">已收货</span>';
            } else if (item.status === 4) {
                refund = '<span class="label label-danger">退款中</span>';
            } else if (item.status === 5) {
                refund = '<span class="label label-danger">售后中</span>';
            } else if (item.status === 6) {
                product_status = '<span class="label label-primary">已完成</span>';
            } else {
                product_status = '';
                refund = '';
            }
            if (item.isKuaidi == 1) {
                var sn = "暂无";
                if (item.kuaidisn != "") {
                    sn = item.kuaidisn;
                }


                info = info
                    + '<table class="table">'
                    + '<tbody>'
                    + '<tr>'
                    + '<td style="width: 50px"><img src=' + item.thumb + ' style="width:50px;height:50px"></td>'
                    + '<td style="border: 0px">' + item.productName + '<br>'
                    + product_status
                    + '</td>'
                    + '<td style="text-align:right;border: 0px">' +
                    '         ' + l + '<br>'
                    + '原价:' + item.productprice + '<br>'
                    + '应付:' + item.marketprice + '<br>'
                    + '数量:' + item.total + '<br>'
                    + '快递单号:' + sn + '<br>'
                    + '收货地址:' + item.province + item.city + item.district + item.address + '<br>'
                    + refund
                    + '</td>'
                    + '</tr>'
                    + '</tbody>'
                    + '</table>'

            } else {
                info = info
                    + '<table class="table">'
                    + '<tbody>'
                    + '<tr>'
                    + '<td style="width: 50px"><img src=' + item.thumb + ' style="width:50px;height:50px"></td>'
                    + '<td style="border: 0px">' + item.productName + '<br>'
                    + product_status
                    + '</td>'
                    + '<td style="text-align:right;border: 0px">' +
                    '         ' + l + '<br>'
                    + '原价:' + item.productprice + '<br>'
                    + '应付:' + item.marketprice + '<br>'
                    + '数量:' + item.total + '<br>'
                    + refund
                    + '</td>'
                    + '</tr>'
                    + '</tbody>'
                    + '</table>'
            }
        }
    }
    return info;
}

/**
 * 订单详情页面
 * @param orderId
 */
function detail(orderId) {
    layer.open({
        id: 'order_detail',
        type: 2,
        title: '订单详情',
        maxmin: true,
        shadeClose: false,
        area: ['60%', '80%'],
        content: prefix + '/detail/' + orderId // iframe的url
    });
}


/**
 * 单品退款
 * @param orderProductId
 */
function refundSingle(orderProductId) {
    layer.confirm('确定要申请退款吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/refundSingle",
            type: "POST",
            data: {
                'orderProductId': orderProductId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}

/**
 * 关闭订单
 * @param orderId
 */
function closeOrder(orderId) {
    layer.confirm('确定要关闭该订单吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/closeOrder",
            type: "POST",
            data: {
                'orderId': orderId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}

/**
 * 退款申请
 * @param orderId
 */
function refundOrder(orderId) {
    layer.confirm('确定要后台申请退款吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/refundOrder",
            type: "POST",
            data: {
                'orderId': orderId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}

/**
 * 退款申请
 * @param orderId
 */
function sendGoods(orderId) {
    layer.confirm('您确定要发货吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/sendGoods",
            type: "POST",
            data: {
                'orderId': orderId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}


/**
 * 退款申请
 * @param orderId
 */
function received(orderId) {
    layer.confirm('您确定要收货吗？', {
        btn: ['确定', '取消']
    }, function () {
        $.ajax({
            url: prefix + "/confirmReceived",
            type: "POST",
            data: {
                'orderId': orderId
            },
            beforeSend: function (request) {
                index = layer.load();
            },
            success: function (r) {
                if (r.code == 0) {
                    layer.close(index);
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    })
}

/**
 * 待收货记录导出
 */
function exportOrders() {
    var queryItem = $.trim($("#queryItem").val());
    var payStatus = $('#payStatus').val();
    var centreId = $("*[name='centreId']").val();
    var province = $('#province').val();
    var city = $('#city').val();
    var start = $('#start').val();
    var end = $('#end').val();
    var dispatchid = $('#dispatchid').val();
    window.location.href = prefix + "/export?centreId=" + centreId + "&queryItem=" + queryItem + "&start=" + start + "&end=" + end +
        "&payStatus=" + payStatus + "&province=" + province + "&city=" + city + "&dispatchid=" + dispatchid;
}

/**
 * 订单详情页面
 * @param orderId
 */
function splitAccountInfo(outTradeNo) {
    layer.open({
        id: 'order_detail',
        type: 2,
        title: '分账信息',
        maxmin: true,
        shadeClose: false,
        area: ['80%', '80%'],
        content: prefix + '/splitAccountInfo?outTradeNo=' + outTradeNo // iframe的url
    });
}

/**
 * 退款详情
 */
function refundInfo(refundNo) {
    layer.open({
        id: 'refund_detail',
        type: 2,
        title: '退款信息',
        maxmin: true,
        shadeClose: false,
        area: ['80%', '80%'],
        content: prefix + '/refundDetail?refundNo=' + refundNo // iframe的url
    });
}